<?php
namespace App\Controller;

/**
 * 守望先锋活动第二期
 * @author liubo <liubo@ilongyuan.com.cn>
 */
class OwController extends AppController
{

    public function _initialize()
    {
        parent::_initialize();
        $config = [
            1 => [
                'start'        => strtotime('2016-09-16 00:00:00'),
                'end'          => strtotime('2016-09-21 23:59:59'),
                'prefix'       => '【突击】',
                'heros'        => '突击类英雄（士兵76、死神、法老之鹰、源氏、猎空、麦克雷）',
            ],
            2 => [
                'start'        => strtotime('2016-09-23 00:00:00'),
                'end'          => strtotime('2016-09-28 23:59:59'),
                'prefix'       => '【防御】',
                'heros'        => '防御类英雄（半藏、堡垒、黑百合、托比昂、狂鼠、美）',
            ],
            3 => [
                'start'        => strtotime('2016-09-30 00:00:00'),
                'end'          => strtotime('2016-10-08 23:59:59'),
                'prefix'       => '【重装】',
                'heros'        => '重装类英雄（D.Va、路霸、查莉娅、温斯顿、莱因哈特）',
            ],
            4 => [
                'start'        => strtotime('2016-10-14 00:00:00'),
                'end'          => strtotime('2016-10-19 23:59:59'),
                'prefix'       => '【支援】',
                'heros'        => '支援类英雄（天使、卢西奥、秩序之光、禅雅塔、安娜）',
            ]
        ];
        $this->game_id = 8; //守望先锋

        $default_type = $this->get_default_type($config);
        $this->type = $type = I('type', $default_type, 'intval');

        foreach ($config as $key => &$value) {
            if (empty($value) || NOW_TIME < $value['start']) {
                $value['status'] = 'future';
            } else if (NOW_TIME >= $value['start'] && NOW_TIME <= $value['end']) {
                $value['status'] = 'ongoing';
            } else {
                $value['status'] = '';
            }
            $value['type'] = $key;
            $value['active'] = $type == $key ?'active':'';
        }

        $_config = $config[$type];
        foreach ($_config as $key1 => $value1) {
            $this->$key1 = $value1;
        }
        $this->assign('typelist',$config);
        $this->assign('type', $type);

        $this->assign('keywords', '66Play短视频,游戏视频录制,OW游戏视频,OW游戏录像,士兵76、死神、法老之鹰、源氏、猎空、麦克雷');
        $this->assign('description', '将守望先锋OW游戏中突击类英雄（士兵76、死神、法老之鹰、源氏、猎空、麦克雷）的精彩视频通过66play软件录制并上传，即可参加活动');

        $this->isClosed = NOW_TIME > $this->end;
    }

    public function index()
    {
        if ($this->isClosed) {
            return $this->finish();
        }
        $p     = I('p', 1, 'intval');
        $pager = I('pager', IS_MOBILE ? 8 : 12, 'intval');

        $sort = I('sort');
        !in_array($sort, ['hot', 'new']) && $sort = 'hot';

        $videos = $this->video($this->prefix, ($p-1)*$pager, $pager, $sort == 'hot' ? 'zan' : 'create_time');
        if (IS_AJAX) {
            $this->ajaxReturn(['state' => 0, 'data' => $videos]);
        }
        $this->assign('videos', $videos);
        $this->assign('pager', $pager);
        if (IS_MOBILE) {
            $token = I('appToken');
            if (!empty($token)) {
                $this->assign('isFromApp', true);
            }
            $this->assign('title', "守望先锋 OW {$this->prefix}英雄 活动专题页【66Play】一键记录你的游戏青春");
            return $this->display('mobile');
        }
        $total = $this->count($this->prefix);
        $this->assign('total', $total);
        $this->assign('title', "守望先锋 OW {$this->prefix}英雄 活动专题页【66Play】一键记录你的游戏青春");
        $this->assign('current_tab', $sort);
        $this->display();
    }

    public function finish()
    {
        $p     = I('p', 1, 'intval');
        $pager = I('pager', 8, 'intval');

        $start = ($p-1)*$pager;
        $videos = $this->video($this->prefix, $start, $pager);

        if (IS_AJAX) {
            $this->ajaxReturn(['state' => 0, 'data' => $videos]);
        }

        $vids = C('OW_WINNER_VIDEOS');
        $vids = explode('.', $vids[$this->type]);
        $winnerVideos = [];
        foreach ($vids as $vid) {
            $v = event('Video')->detail((int)$vid);
            $v && $winnerVideos[] = $v;
        }

        $this->assign('winnerVideos', $winnerVideos);
        $this->assign('videos', $videos);
        $this->assign('pager', $pager);
        if (IS_MOBILE) {
            $token = I('appToken');
            if (!empty($token)) {
                $this->assign('isFromApp', true);
            }
            $this->assign('title', "守望先锋 OW {$this->prefix}英雄 活动专题页【66Play】一键记录你的游戏青春");
            return $this->display('mobile_end');
        }
        $this->assign('title', "守望先锋 OW {$this->prefix}英雄 活动专题页【66Play】一键记录你的游戏青春");
        $total = $this->count($this->prefix);
        $this->assign('total', $total);
        $this->display('index_end');
    }

    private function video($prefix, $offset = 0, $limit = 12, $order = 'zan')
    {
        $service = D('Video', 'Service');

        $map['title'] = new \MongoRegex("/^$prefix/i");
        $map['status'] = $service::STATUS_PASS;
        $map['type'] = $service::TYPE_NORMAL;
        $map['race_id'] = ['$eq' => null];
        $map['game_id'] = $this->game_id;
        if (!empty($this->start) && !empty($this->end)) {
            $map['create_time'] = ['$gte' => $this->start, '$lte' => $this->end];
        }
        $res = $service->where($map)->field('id')->select();

        $vEvent = event('video');
        $likeService = service('Like');

        $fieldMap = ['id', 'title', 'create_time', 'time', 'user', 'statis', 'uri', 'pre_uri', 'thumb'];
        $list = [];
        foreach ($res as $key => $value) {
            $vid = $value['id'];
            $video = $vEvent->detail($vid);

            $condition = [
                'create_time' => ['$gte' => $this->start, '$lte' => $this->end],
                'target_id'   => $vid,
                'type'        => $likeService::TYPE_VIDEO
            ];
            $video['statis']['zan'] = $likeService->where($condition)->count();
            $video = $this->field_filter($video, $fieldMap);
            $list[] = $video;
        }

        foreach ($list as $key => $value) {
            $likeCount[$key] = $value['statis']['zan'];
            $createTime[$key] = $value['create_time'];
        }

        if ($order == 'zan') {
            array_multisort($likeCount, SORT_DESC, $createTime, SORT_ASC, $list);
        } else {
            array_multisort($createTime, SORT_DESC, $list);
        }

        $list = array_slice($list, $offset, $limit);

        return $list;
    }

    private function count($prefix) {
        $service = D('Video', 'Service');
        $map['title'] = new \MongoRegex("/^$prefix/i");
        $map['status'] = $service::STATUS_PASS;
        $map['type'] = $service::TYPE_NORMAL;
        $map['race_id'] = ['$eq' => null];
        $map['game_id'] = $this->game_id;
        if (!empty($this->start) && !empty($this->end)) {
            $map['create_time'] = ['$gte' => $this->start, '$lte' => $this->end];
        }
        return $service->where($map)->count();
    }

    public function get_default_type($config)
    {
        $type = 1;
        foreach ($config as $key => $value) {
            if (!empty($value) && NOW_TIME >= $value['start']) {
                $type = $key;
            }
        }
        return $type;
    }
}